import { Component, OnInit, Input, OnDestroy } from "@angular/core";
import { AppGlobalService } from "src/app/shared/service/app-global.service";
import { SearchListService } from "src/app/shared/service/search-list.service";
import { IndexedDBService } from "src/app/shared/service/indexed-db.service";
import { AlertController } from '@ionic/angular';
import { EventService } from 'src/app/shared/service/event.service';
import { HttpService } from 'src/app/shared/service/http.service';

@Component({
  selector: "app-last-contact-list",
  templateUrl: "./last-contact-list.component.html",
  styleUrls: ["./last-contact-list.component.scss"]
})
export class LastContactListComponent implements OnInit, OnDestroy {
  @Input() tagData: any;

  key: any; // 搜索参数

  subscription: any; // 广播对象

  listData: any[]; // 列表数据

  constructor(
    private appGlobalService: AppGlobalService,
    private indexedDBService: IndexedDBService,
    private broadcast: SearchListService,
    private alert: AlertController,
    public eventService: EventService,
    public httpService: HttpService,
  ) { }

  ngOnInit() {
    // 后台返回数据
    if (!this.tagData.localSource) {
      this.listData = this.tagData.data.data;
    } else {
      // 本地获取列表数据
      this.indexedDBService.getLastContactCustomerList(list => {
        console.log("msg----->最近联系客户list=", list);
        this.listData = list;
      });
    }

    // 接收广播筛选条件
    this.subscription = this.broadcast.getMessage().subscribe(res => {
      if (res.type === "filter") {
        this.key = res.value;
      } else if (res.type === "submit" && this.tagData.submitId === res.id) {
        if (res.value.data) {
          this.listData = res.value.data.data;
        }
      }
    });
  }
// 短信确认弹框
  async go(obj, nickname) {
    if (obj.link && obj.link.type === 'chat') {
      const msgStr = '确定发送' + (obj.link.params.entranceType ? '消息' : '案例') + '给' + nickname + '吗？';
      const alert = await this.alert.create({
        message: msgStr,
        buttons: [
          {
            text: '取消',
            role: 'cancel',
            cssClass: 'secondary',
            handler: () => {
            }
          }, {
            text: '确定',
            cssClass: 'LJ',
            handler: () => {
              // 发送案例消息 add by andrew.wen
              if (localStorage.getItem('userId') !== 'null') {
                const nowDate = Date.now();
                const uid = localStorage.getItem('userId');
                const positionInfo = JSON.parse(localStorage.getItem('position'));
                const item = { id: obj.id + '-' + localStorage.getItem('userId'), toId: obj.id, type: 'pxw' };
                if (obj.link.params.entranceType) {
                  // 发送商机消息 add by andrew.wen
                  if (localStorage.getItem('shareOppDetail')) {
                    const oppDetail = JSON.parse(localStorage.getItem('shareOppDetail'));
                    // localStorage.removeItem('shareOppDetail');
                    localStorage.setItem('onSendWebSocketMessageTag', 'true');
                    const shareFromUserId = localStorage.getItem("connUserId");
                    const message = {
                      text: oppDetail.title,
                      toId: item.toId,
                      fromId: shareFromUserId,
                      key: item.id,
                      type: 'opp',
                      rentunit: oppDetail.rentunit ? oppDetail.rentunit : '元/月',
                      opportunity_id: oppDetail.opportunity_id,
                      title: oppDetail.title,
                      imags: oppDetail.imags ? oppDetail.imags : '../../../assets/img/375x250@2x.png',
                      pluginId: oppDetail.pluginId,
                      big_district: oppDetail.big_district ? oppDetail.big_district : '',
                      district: oppDetail.district ? oppDetail.district : '',
                      area: oppDetail.area ? oppDetail.area : '',
                      industry: oppDetail.industry ? oppDetail.industry : '',
                      rent: oppDetail.rent ? oppDetail.rent : '',
                      transfer_fee: oppDetail.transfer_fee ? oppDetail.transfer_fee : '',
                      nowDate
                    };
                    this.eventService.eventEmit.emit("onSendWebSocketMessage", message);
                    this.appGlobalService.showToast('发送成功', 2000, 'middle');
                  }
                } else {
                  const caseDetail = JSON.parse(localStorage.getItem('caseDetail'));
                  if (obj.id === null || obj.id === "") {
                    if (obj.link.params.customer_id) {
                      this.httpService.getImId(
                        undefined,
                        obj.link.params.customer_id, positionInfo.code ? positionInfo.code : 4403, (resItem) => {
                          localStorage.setItem('onSendWebSocketMessageTag', 'true');
                          this.eventService.eventEmit.emit("onSendWebSocketMessage",
                            {
                              text: caseDetail.title,
                              toId: resItem.toId,
                              fromId: uid,
                              key: resItem.id,
                              type: 'case',
                              title: caseDetail.title,
                              imags: caseDetail.imageUrl ? caseDetail.imageUrl.url : 'assets/img/default_img.png',
                              caseType: '1',
                              district: 4403,
                              serviceDays: caseDetail.time,
                              serviceOpinion: caseDetail.stars,
                              industry: 1101,
                              link: caseDetail.link,
                              nowDate
                            });
                          this.appGlobalService.showToast('发送成功', 2000, 'middle');
                        });
                    }
                  } else {
                    localStorage.setItem('onSendWebSocketMessageTag', 'true');
                    this.eventService.eventEmit.emit("onSendWebSocketMessage",
                      {
                        text: caseDetail.title,
                        toId: item.toId,
                        fromId: uid,
                        key: item.id,
                        type: 'case',
                        title: caseDetail.title,
                        imags: caseDetail.imageUrl ? caseDetail.imageUrl.url : 'assets/img/default_img.png',
                        caseType: '1',
                        district: 4403,
                        serviceDays: caseDetail.time,
                        serviceOpinion: caseDetail.stars,
                        industry: 1101,
                        link: caseDetail.link,
                        nowDate
                      });
                    this.appGlobalService.showToast('发送成功', 2000, 'middle');
                  }
                }
              }
            }
          }
        ]
      });
      await alert.present();
    } else {
      const pageParams = {
        pageId: obj.target,
        params: obj.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(pageParams);
    }
  }

  ngOnDestroy(): void {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}
